#!/usr/bin/python

from PIL import Image

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
from reportlab.lib.colors import black, white, gray, lightgrey,  darkgray,  red
from reportlab.lib.pagesizes import letter
from reportlab.lib.utils import ImageReader, LazyImageReader
from reportlab.platypus.tables import LINECAPS

import pprint

from hgbfe.perks import auxPerks, defensePerks, ewPerks, miscPerks, movementPerks, weaponPerks
from hgbfe.weapon import weaponCmp
from hgbfe.trait import traitCmp

cWidth = 252
cHeight  = 180
padding = 2
LINE_WIDTH = 0.1

stripeImage = "images/hazard_stripe.png"
infoImages = {
    "movement" : "images/arrows/arrow_wb.png",
    "ew" : "images/arrows/arrow_wb.png",    
    "ranged" : "images/arrows/arrow_wb.png",
    "armor" : "images/arrows/arrow_wb.png",
    "defense" : "images/arrows/arrow_wb.png",
    "melee" : "images/arrows/arrow_wb.png",
    "aux" : "images/arrows/arrow_wb.png",
    "misc" : "images/arrows/arrow_wb.png",
}
factionImages = {
    "north": "images/icons/icon_north.png",
    "south": "images/icons/icon_south.png",
    "prdf": "images/icons/icon_prdf.png",
    "pak": "images/icons/icon_pak.png",
}

pdfmetrics.registerFont(TTFont('LS-Bold', 'fonts/LiberationSans-Bold.ttf'))
pdfmetrics.registerFont(TTFont('LS', 'fonts/LiberationSans-Regular.ttf'))

def drawBorder(canvas, origin):
    canvas.setLineWidth(LINE_WIDTH)
    canvas.rect(origin[0], origin[1], cWidth, cHeight)
    canvas.rect(origin[0] + cWidth,  origin[1] ,  cWidth,  cHeight)
    
    # TODO: Add a dashed line for the 'bend here' idea?
    #canvas.line(origin[0] + cWidth,  origin[0] + cHeight,  origin[0] + cWidth,  origin[0])

def drawBackground(canvas, origin):
    stripe = ImageReader(stripeImage)
    
    canvas.drawImage(stripe, origin[0] + 0, origin[1] + 0, width=20, height=50)
    canvas.drawImage(stripe, origin[0] + 0, origin[1] + 49, width=20, height=50)
    canvas.drawImage(stripe, origin[0] + 0, origin[1] + 98, width=20, height=50)
    canvas.drawImage(stripe, origin[0] + 0, origin[1] + 147, width=20, height=33)
    
    iconImage = ImageReader(factionImages['north'])
    iconX = 2
    iconY = origin[1] + cHeight - 34
    #print "Drawing icon at coords (%i, %i)" % (iconX,  iconY)
    canvas.drawImage(iconImage, iconX, iconY, 
                    mask=(0,0,0,0,0,0), width=32, height=32)
   
def drawTitle(canvas, origin, name,  modelCount):
    
    titleX = origin[0] + cWidth - 2
    titleY = origin[1] + cHeight - 9
    titleHeight = (origin[1] + cHeight) - 11
    
    canvas.setFont("LS-Bold", 9)    
    canvas.setFillColor(black)
    canvas.drawRightString(titleX,  titleY, name)
    
    canvas.setStrokeColor(black)
    canvas.line((origin[0] + cWidth ) - 140, titleHeight+1, (origin[0] + cWidth) - padding, titleHeight+1)
    
    watermarkX = (cHeight * modelCount) + 4
    watermarkY = -14
    
    #print "Drawing HGB-FE watermark at coordinates (%i, %i)" % (watermarkX,  watermarkY)
    canvas.setFont("LS-Bold", 12)
    canvas.setFillColor(white)
    canvas.rotate(90)
    canvas.drawString(watermarkX,  watermarkY, "HGB-FE")
    canvas.rotate(-90)

# Older methods below here

def drawArmor(canvas, origin,  damageDict):
    
    boxWidth = 42
    boxHeight = 81
    boxLeftX = (origin[0]) + 22        
    boxTopY = (origin[1]) + boxHeight + padding

    # how wide the box is
    boxDims = 8 
    squareCenterX = (boxLeftX + (boxWidth / 2)) 
    squareLeftX = (boxLeftX + (boxWidth / 2)) - (boxDims / 2)    
    frontX = squareLeftX - padding
    rearX = squareLeftX + padding + boxDims

    # Draw the border first
    canvas.setStrokeColor(black)    
    canvas.setFillColor(white)
    print "Drawing box at (%i, %i) with dims (%i, %i)" % (boxLeftX,  boxTopY - boxHeight,  boxWidth,  boxHeight)
    canvas.rect(boxLeftX,  boxTopY - boxHeight,  boxWidth,  boxHeight)
    canvas.setFillColor(black)

    # Create the black text box
    titleY = boxTopY - 5
    canvas.rect(boxLeftX, titleY , boxWidth, 5,  stroke=0,  fill=1)    
    canvas.line(boxLeftX, titleY , boxLeftX + boxWidth, titleY )
    canvas.setFillColor(white)
    canvas.setFont("LS-Bold", 4)
    canvas.drawString(boxLeftX + 2, boxTopY - 4, "DAMAGE")
    
    # Create our header
    headerY = boxTopY - 11
    headerHeight = 5
    headerY = titleY - headerHeight
    canvas.setFillColor(white)
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, headerY, boxWidth, headerHeight, stroke=1, fill=0)
    canvas.setFillColor(black)
    canvas.setFont("LS", 4)
    canvas.drawRightString(frontX, headerY + 1 , "FRONT")    
    canvas.drawString(rearX, headerY + 1, "REAR")    
        
    # Now create the boxes    
    canvas.setFont("LS", 5)
    canvas.setFillColor(black)
    canvas.setStrokeColor(black)
    
    # Where the box starts on the line
    squareStartY = headerY - headerHeight * 2
    
    for idx in range(7):
        boxDict = damageDict[idx]
        squareBottomY = squareStartY - (idx * (boxDims + padding))
        frontS = boxDict['front']
        rearS = boxDict['rear']
        
        # Determine if we need to do the background first        
        if 'unused' in boxDict:
            canvas.setStrokeColor(lightgrey)
        else:
            canvas.setStrokeColor(black)

        if 'boxType' in boxDict:
            boxType = boxDict['boxType'].upper()
            
            if boxType =='H':
                canvas.setFillColor(lightgrey)
                canvas.rect(boxLeftX,  squareBottomY - 1, boxWidth,  boxDims + 2,  fill=1,  stroke=0)
                canvas.setFillColor(black)
            elif boxType == 'C':
                canvas.setFillColor(darkgray)
                canvas.rect(boxLeftX,  squareBottomY - 1, boxWidth,  boxDims + 2,  fill=1,  stroke=0)
                canvas.setFillColor(black)
            elif boxType == 'D':
                canvas.setFillColor(black)
                canvas.setStrokeColor(white)
                canvas.rect(boxLeftX,  squareBottomY - 1, boxWidth,  boxDims + 2,  fill=1,  stroke=0)
                canvas.setFillColor(white)
                canvas.setStrokeColor(white)                
                
            canvas.drawRightString(frontX,  squareBottomY  + 2,  boxDict['front'])
            canvas.drawString(rearX, squareBottomY + 2, boxDict['rear'])
            canvas.drawCentredString(squareCenterX,  squareBottomY +2,  boxDict['boxType'].upper())            
        
        canvas.rect(squareLeftX,  squareBottomY,  boxDims,  boxDims)        

def drawMovement(canvas, origin, moveDict):
    # Define our diminsions
    origin_x = origin[0]
    origin_y = origin[1]
    
    boxWidth = 80
    boxHeight = 22
    boxLeftX = (origin_x + cWidth) - (boxWidth + padding + 78)
    boxBottomY = (origin_y + cHeight) - boxHeight - 20
    
    titleHeight = 5
    headerHeight = 5
    zebraStripeHeight = 6    
    lineHeight = 5
    
    titleBottomY = boxBottomY + boxHeight - titleHeight
    headerBottomY = titleBottomY - headerHeight
    zebraStartY = headerBottomY
    numStripes = 2
    lineStartY = headerBottomY - lineHeight - padding
    
    xCoordDict = {}
    startX = boxLeftX + 2  
    xCoordDict['type'] = startX    
    xCoordDict['points'] = startX + 38
    xCoordDict['atk'] = startX + 54
    xCoordDict['def'] = startX + 68

    # First, draw our zebra striping for the different movement modes
    drawZebraStripes(canvas,  boxLeftX,  boxWidth,  zebraStartY,  numStripes,  zebraStripeHeight)
    
    # Draw title first
    titleHeight = 5
    titleY = boxBottomY + boxHeight - 5
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, titleY, boxWidth, titleHeight, stroke=0, fill=1)
    canvas.setFillColor(white)
    canvas.setFont("LS-Bold", 4)
    canvas.drawString(boxLeftX + padding, titleY + 1, "MOVEMENT")    
    
    # Now header
    headerHeight = 5
    headerY = titleY - headerHeight
    canvas.setFillColor(white)
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, headerY, boxWidth, headerHeight, stroke=1, fill=0)
    canvas.setFillColor(black)
    canvas.setFont("LS", 4)
    canvas.drawString( xCoordDict['type'] , headerY + 1 , "TYPE")
    canvas.drawRightString(xCoordDict['points'] , headerY + 1, "MP")
    canvas.drawRightString(xCoordDict['atk'], headerY + 1, "ATK") 
    canvas.drawRightString(xCoordDict['def'], headerY + 1, "DEF") 
    
    # Now the datalines
    for idx in range(2):
        if idx in moveDict:            
            typeDict = moveDict[idx]
            typeY= lineStartY - (idx * (lineHeight + 1)) + padding
            drawMoveLine(canvas,  xCoordDict,  typeY,  padding,  typeDict)

    # Finally, outline the entire box
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, boxBottomY, boxWidth, boxHeight,  stroke=1)

def drawMoveLine(canvas,  xCoordDict,  yCoord,  padding,  typeDict):    
    canvas.setFillColor(black)
    canvas.setStrokeColor(black) 
    canvas.setFont("LS", 5)
    
    canvas.drawString(xCoordDict['type'], yCoord, typeDict["type"])
    movePointS = "%s" % (typeDict['movePoints'])
    canvas.drawRightString(xCoordDict['points'], yCoord, movePointS)
    canvas.drawRightString(xCoordDict['atk'], yCoord, typeDict["atkMod"])
    canvas.drawRightString(xCoordDict['def'], yCoord, typeDict["defMod"])
    
def drawEW(canvas, origin, ewDict):    
    boxWidth = 80
    boxHeight = 22
    boxLeftX = (origin[0] + cWidth) - (boxWidth + padding + 78) 
    boxBottomY = (origin[1] + cHeight) - boxHeight - 45
    boxTitleBottomY = boxBottomY + boxHeight - 4

    titleHeight = 5
    headerHeight = 5
    zebraStripeHeight = 6    
    lineHeight = 5

    zebraStartY = boxTitleBottomY
    numStripes = 3
    lineStartY = boxTitleBottomY - lineHeight - padding

    # Line positions
    lineWidth = 3 + padding
    lineThreeY = boxBottomY + 1
    lineTwoY   = lineThreeY + lineHeight + 1
    lineOneY   = lineTwoY + lineHeight + 1

    labelOneX = boxLeftX + padding
    labelTwoX = labelOneX + (boxWidth/2) - padding
    valueOneX = labelTwoX - padding
    valueTwoX = boxLeftX + boxWidth - padding

    # First, draw our zebra striping for the different movement modes
    drawZebraStripes(canvas,  boxLeftX,  boxWidth,  zebraStartY,  numStripes,  zebraStripeHeight)
    
    # Draw our title
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, boxTitleBottomY, boxWidth, titleHeight, stroke=0, fill=1) # black title
    canvas.setFillColor(white)
    canvas.setFont("LS-Bold", 4)
    canvas.drawString(boxLeftX + padding, boxTitleBottomY + (padding/2), "EW")

    # Draw the Labels
    canvas.setFont("LS", 5)    
    canvas.setFillColor(black)
    
    canvas.drawString(labelOneX, lineOneY, "Detect:")
    canvas.drawRightString(valueOneX, lineOneY, str(ewDict['detect']))
    
    canvas.drawString(labelTwoX, lineOneY, "Auto Comm:")
    canvas.drawRightString(valueTwoX, lineOneY, str(ewDict['autocomm']))
    
    canvas.drawString(labelOneX, lineTwoY, "Sensors:")
    sensorsS = "%+i" % ewDict['sensors']
    canvas.drawRightString(valueOneX, lineTwoY, sensorsS)
    
    canvas.drawString(labelTwoX, lineTwoY, "Comm:")
    commS= "%+i" % ewDict['comm']
    canvas.drawRightString(valueTwoX, lineTwoY, commS)
    
    if  not'ecm' in ewDict or ewDict['ecm'] == 0:
        canvas.setFillColor(lightgrey)
        canvas.drawRightString(valueOneX, lineThreeY, "NA")
    else:
        canvas.setFillColor(black)
        ecmS = "%+i" % ewDict['ecm']
        canvas.drawRightString(valueOneX, lineThreeY, ecmS)
    canvas.drawString(labelOneX, lineThreeY, "ECM:")
    
    if  not'eccm' in ewDict or ewDict['eccm'] == 0:
        canvas.setFillColor(lightgrey)
        canvas.drawRightString(valueTwoX, lineThreeY, "NA")
    else:
        canvas.setFillColor(black)
        eccmS = "%+i" % ewDict['eccm']
        canvas.drawRightString(valueTwoX, lineThreeY, eccmS)    
    canvas.drawString(labelTwoX, lineThreeY, "ECCM:")
    
    # Finally draw the outline
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, boxBottomY, boxWidth, boxHeight, stroke=1, fill=0) # outline
    
def drawLD(canvas, origin, leadership, priorityLevel):    
    boxWidth = 80
    boxHeight = 26
    boxLeftX = (origin[0] + cWidth) - (boxWidth + padding + 78) 
    boxBottomY = (origin[1] + cHeight) - boxHeight - 69
    boxTitleBottomY = boxBottomY + boxHeight - 4

    titleHeight = 5
    labelX = boxLeftX + padding
    boxStartX = labelX + 30

    # Line positions    
    lineHeight = 6
    lineThreeY = boxBottomY + 1
    lineTwoY   = lineThreeY + lineHeight + 1
    lineOneY   = lineTwoY + lineHeight + 1

    labelOneX = boxLeftX + padding
    labelTwoX = labelOneX + (boxWidth/2) - padding
    valueOneX = labelTwoX - padding
    valueTwoX = boxLeftX + boxWidth - padding

    # First, draw our zebra striping for the different movement modes
    
    # Draw our title
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, boxTitleBottomY, boxWidth, titleHeight, stroke=0, fill=1) # black title
    canvas.setFillColor(white)
    canvas.setFont("LS-Bold", 4)
    canvas.drawString(boxLeftX + padding, boxTitleBottomY + (padding/2), "LEADERSHIP")
    
    canvas.setFont("LS", 5)
    canvas.setFillColor(black)
    canvas.drawString(labelX, lineOneY + 1, "Command")
    canvas.drawString(labelX, lineTwoY + 1, "Demoralized")
    canvas.drawString(labelX, lineThreeY + 1, "Broken")
    
    priorityThreshold = priorityLevel + leadership
    boxDims = 6
    
    canvas.setStrokeColor(black)    
    for idx in range(6):
        if (leadership < idx+1):
            canvas.setStrokeColor(lightgrey)
        posX = (boxStartX) + (padding + boxDims) * idx
        canvas.rect(posX, lineOneY, boxDims, boxDims, stroke=1, fill=0)

    canvas.setStrokeColor(black)
    for idx in range(6):
        if (priorityThreshold < idx+1):
            canvas.setStrokeColor(lightgrey)
        posX = (boxStartX) + (padding + boxDims) * idx
        canvas.rect(posX, lineTwoY, boxDims, boxDims, stroke=1, fill=0)
        
    canvas.setStrokeColor(black)
    for idx in range(6):
        if (priorityThreshold < idx+1):
            canvas.setStrokeColor(lightgrey)
        posX = (boxStartX) + (padding + boxDims) * idx
        canvas.rect(posX, lineThreeY, boxDims, boxDims, stroke=1, fill=0)
    
    # Finally draw the outline
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, boxBottomY, boxWidth, boxHeight, stroke=1, fill=0) # outline    
    
def drawRangedWeapons(canvas, origin,  weaponsDict):    
    boxWidth = 184
    boxLeftX = (origin[0] +cWidth) - (boxWidth + padding)    
    boxHeight = 46
    boxTopY = (origin[1]) + boxHeight + padding + 35
    
    titleHeight = 5
    headerHeight = 5
    zebraStripeHeight = 6    
    lineHeight = 5
    
    titleBottomY = boxTopY - titleHeight
    headerBottomY = titleBottomY - headerHeight
    zebraStartY = headerBottomY
    numStripes = 6
    lineStartY = headerBottomY - lineHeight - padding
    
    xCoordDict = {}
    startX = boxLeftX + padding
    xCoordDict['name'] = startX
    xCoordDict['arc'] = startX + 26
    xCoordDict['rangePR'] = startX + 42
    xCoordDict['rangeCR'] = startX + 54 
    xCoordDict['rangeER'] = startX + 66
    xCoordDict['damage'] = startX + 70
    xCoordDict['special'] = startX + 82
    xCoordDict['ammo'] = (boxWidth + boxLeftX) - padding
    
    # First, draw our zebra striping for the different weapon
    drawZebraStripes(canvas,  boxLeftX,  boxWidth,  zebraStartY,  numStripes,  zebraStripeHeight)

    # Draw our title bar
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, titleBottomY,  boxWidth, titleHeight,  stroke=0, fill=1)   
    canvas.setFillColor(white)    
    canvas.setFont("LS-Bold", 4)
    canvas.drawString(boxLeftX + padding, boxTopY- (titleHeight-1), "RANGED WEAPONS")

    # Draw our line headers
    canvas.setFillColor(black)
    canvas.setStrokeColor(black)
    canvas.setFont("LS", 4)
    canvas.line(boxLeftX, headerBottomY,  boxLeftX+boxWidth, headerBottomY)
    drawRngWeapHeaders(canvas,  xCoordDict,  headerBottomY + 1)
    
    # Finally draw our lines    
    for idx in range(6):
        if idx in weaponsDict:
            weaponDict = weaponsDict[idx]
            weaponY = lineStartY - (idx * (lineHeight + 1))
            drawRngWeapLine(canvas,  xCoordDict,  weaponY  + 2,  padding,  weaponDict)
    
     # Finally, outline the entire box
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, boxTopY - boxHeight, boxWidth, boxHeight,  stroke=1)
    
def drawRngWeapHeaders(canvas,  xCoordDict,  headerY):
    canvas.setFillColor(black)
    canvas.setStrokeColor(black)    
    canvas.setFont("LS", 4)
    
    canvas.drawString(xCoordDict['name'], headerY, "NAME")
    canvas.drawString(xCoordDict['arc'], headerY, "ARC")
    canvas.drawCentredString(xCoordDict['rangeCR'] - padding,  headerY, "RANGE")
    canvas.drawString(xCoordDict['damage'],  headerY, "DAM")
    canvas.drawString(xCoordDict['special'], headerY, "SPECIAL") 
    canvas.drawRightString(xCoordDict['ammo'], headerY, "AMMO") 
    
def drawRngWeapLine(canvas,  xCoordDict,  yCoord,  padding,  weaponDict):    
    canvas.setFillColor(black)
    canvas.setStrokeColor(black) 
    canvas.setFont("LS", 5)
    
    canvas.drawString(xCoordDict['name'], yCoord, weaponDict["name"])
    canvas.drawString(xCoordDict['arc'], yCoord, weaponDict["arc"])    
    
    canvas.drawRightString(xCoordDict['rangePR'], yCoord, weaponDict["rangePR"])
    canvas.drawString(xCoordDict['rangePR'] + padding,  yCoord, "/")
    
    canvas.setFont("LS-Bold", 5)
    canvas.drawRightString(xCoordDict['rangeCR'], yCoord, weaponDict["rangeCR"])
    
    canvas.setFont("LS", 5)
    canvas.drawString(xCoordDict['rangeCR'] + padding, yCoord, "/")
    canvas.drawRightString(xCoordDict['rangeER'], yCoord, weaponDict["rangeER"])
    
    canvas.drawString(xCoordDict['damage'], yCoord, "x%s" % weaponDict["dam"])

    specialLabel = "-"
    if "special" in weaponDict:
        specialLabel = weaponDict["special"]
    canvas.drawString(xCoordDict['special'], yCoord, specialLabel)

    if "ammo" in weaponDict:
        ammoS = "O" * int(weaponDict["ammo"])
        canvas.drawRightString(xCoordDict['ammo'], yCoord, ammoS)

def drawThrownWeapons(canvas, origin,  weaponsDict):
    boxWidth = 96
    boxLeftX = (origin[0]) + 66
    boxHeight = (origin[0]) + 34
    boxTopY = (origin[1]) + boxHeight + padding
    
    titleHeight = 5
    headerHeight = 5
    zebraStripeHeight = 6    
    lineHeight = 5
    
    titleBottomY = boxTopY - titleHeight
    headerBottomY = titleBottomY - headerHeight
    zebraStartY = headerBottomY
    numStripes = 4
    lineStartY = headerBottomY - lineHeight
    
    xCoordDict = {}
    startX = boxLeftX + padding
    xCoordDict['name'] = startX    
    xCoordDict['range'] = startX + 28
    xCoordDict['damage'] = startX + 36
    xCoordDict['special'] = startX + 48
    xCoordDict['ammo'] = (boxWidth + boxLeftX) - padding
    
    # First, draw our zebra striping for the different weapon
    drawZebraStripes(canvas,  boxLeftX,  boxWidth,  zebraStartY,  numStripes,  zebraStripeHeight)
  
    # Draw the title box
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, titleBottomY,  boxWidth, titleHeight,  stroke=0, fill=1)    
    canvas.setFillColor(white)    
    canvas.setFont("LS-Bold", 4)
    canvas.drawString(boxLeftX + padding, boxTopY- (titleHeight-1), "THROWN WEAPONS")
        
    # Draw the line headers
    canvas.setFillColor(black)
    canvas.setStrokeColor(black)
    canvas.setFont("LS", 4)
    canvas.line(boxLeftX, headerBottomY,  boxLeftX+boxWidth, headerBottomY)
    drawThrownWeapHeaders(canvas,  xCoordDict,  headerBottomY + 1)

    # Now draw the lines
    for idx in range(6):
        if idx in weaponsDict:            
            weaponDict = weaponsDict[idx]
            weaponY = lineStartY - (idx * (lineHeight + 1))
            drawThrownWeapLine(canvas,  xCoordDict,  weaponY,  padding,  weaponDict)

    # Finally, outline the entire box
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, boxTopY - boxHeight, boxWidth, boxHeight,  stroke=1)

def drawThrownWeapHeaders(canvas,  xCoordDict,  headerY):
    canvas.setFillColor(black)
    canvas.setStrokeColor(black)    
    canvas.setFont("LS", 4)
    
    canvas.drawString(xCoordDict['name'], headerY, "NAME")    
    canvas.drawCentredString(xCoordDict['range'] - padding,  headerY , "RANGE")
    canvas.drawString(xCoordDict['damage'],  headerY , "DAM")
    canvas.drawString(xCoordDict['special'], headerY , "SPECIAL") 
    canvas.drawRightString(xCoordDict['ammo'], headerY , "AMMO")     
    
def drawThrownWeapLine(canvas,  xCoordDict,  yCoord,  padding,  weaponDict):    
    canvas.setFillColor(black)
    canvas.setStrokeColor(black) 
    canvas.setFont("LS", 5)
    
    canvas.drawString(xCoordDict['name'], yCoord, weaponDict["name"])    
    canvas.drawRightString(xCoordDict['range'], yCoord, weaponDict["range"])    

    damageS = "x" + weaponDict["dam"]
    canvas.drawString(xCoordDict['damage'], yCoord, damageS)

    specialLabel = "-"
    if "special" in weaponDict:
        specialLabel = weaponDict["special"]
    canvas.drawString(xCoordDict['special'], yCoord, specialLabel)

    if "ammo" in weaponDict:
        ammoS = "O" * weaponDict["ammo"]        
        canvas.drawRightString(xCoordDict['ammo'], yCoord, ammoS)
    
def drawMeleeWeapons(canvas, origin,  weaponsDict):
    boxWidth = 86
    boxLeftX = (origin[0] + cWidth) - (boxWidth + padding)
    boxHeight = (origin[0]) + 34
    boxTopY = (origin[1]) + boxHeight + padding
    
    titleHeight = 5
    headerHeight = 5
    zebraStripeHeight = 6    
    lineHeight = 5
    
    titleBottomY = boxTopY - titleHeight
    headerBottomY = titleBottomY - headerHeight
    zebraStartY = headerBottomY
    numStripes = 4
    lineStartY = headerBottomY - lineHeight
    
    xCoordDict = {}
    startX = boxLeftX + padding
    xCoordDict['name'] = startX    
    xCoordDict['damage'] = startX + 20
    xCoordDict['special'] = startX + 34
    xCoordDict['ammo'] = (boxWidth + boxLeftX) - padding
    
    # First, draw our zebra striping for the different weapon
    drawZebraStripes(canvas,  boxLeftX,  boxWidth,  zebraStartY,  numStripes,  zebraStripeHeight)
  
    # Draw the title box
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, titleBottomY,  boxWidth, titleHeight,  stroke=0, fill=1)    
    canvas.setFillColor(white)    
    canvas.setFont("LS-Bold", 4)
    canvas.drawString(boxLeftX + padding, boxTopY- (titleHeight-1), "MELEE WEAPONS")
        
    # Draw the line headers
    canvas.setFillColor(black)
    canvas.setStrokeColor(black)
    canvas.setFont("LS", 4)
    canvas.line(boxLeftX, headerBottomY,  boxLeftX+boxWidth, headerBottomY)
    drawMeleeWeapHeaders(canvas,  xCoordDict,  headerBottomY + 1)

    # Now draw the lines
    for idx in range(6):
        if idx in weaponsDict:            
            weaponDict = weaponsDict[idx]
            weaponY = lineStartY - (idx * (lineHeight + 1))
            drawMeleeWeapLine(canvas,  xCoordDict,  weaponY,  padding,  weaponDict)

    # Finally, outline the entire box
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, boxTopY - boxHeight, boxWidth, boxHeight,  stroke=1)

def drawMeleeWeapHeaders(canvas,  xCoordDict,  headerY):
    canvas.setFillColor(black)
    canvas.setStrokeColor(black)    
    canvas.setFont("LS", 4)
    
    canvas.drawString(xCoordDict['name'], headerY, "NAME")    
    canvas.drawString(xCoordDict['damage'],  headerY , "DAM")
    canvas.drawString(xCoordDict['special'], headerY , "SPECIAL") 
    canvas.drawRightString(xCoordDict['ammo'], headerY , "AMMO")     
    
def drawMeleeWeapLine(canvas,  xCoordDict,  yCoord,  padding,  weaponDict):    
    canvas.setFillColor(black)
    canvas.setStrokeColor(black) 
    canvas.setFont("LS", 5)
    
    canvas.drawString(xCoordDict['name'], yCoord, weaponDict["name"]) 
    damageS = "x" + weaponDict["dam"]
    canvas.drawString(xCoordDict['damage'], yCoord, damageS)

    specialLabel = "-"
    if "special" in weaponDict:
        specialLabel = weaponDict["special"]
    canvas.drawString(xCoordDict['special'], yCoord, specialLabel)

    if "ammo" in weaponDict:
        ammoS = "O" * weaponDict["ammo"]        
        canvas.drawRightString(xCoordDict['ammo'], yCoord, ammoS)
    
def drawSkills(canvas, origin):
    #boxWidth = 42
    boxWidth = 26
    boxHeight = 29
    #boxLeftX = (origin[0]) + 22
    boxLeftX = (origin[0]) + 65
    diceLeftX = boxLeftX + 18
        
    boxTopY = (origin[1]) + boxHeight + padding + 83
    boxBottomY = boxTopY - boxHeight

    titleHeight = 5
    headerHeight = 5
    zebraStripeHeight = 6    
    lineHeight = 5
    
    titleBottomY = boxTopY - titleHeight
    zebraStartY = titleBottomY
    numStripes = 4
    lineStartY = titleBottomY - lineHeight
    
    # First, draw our zebra striping for the different weapon
    drawZebraStripes(canvas,  boxLeftX,  boxWidth,  zebraStartY,  numStripes,  zebraStripeHeight)
  
    # Draw the title box
    canvas.setStrokeColor(black)
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, titleBottomY,  boxWidth, titleHeight,  stroke=0, fill=1)    
    canvas.setFillColor(white)    
    canvas.setFont("LS-Bold", 4)
    canvas.drawString(boxLeftX + padding, boxTopY- (titleHeight-1), "SKILLS")
    
    # Draw the black left-most box
    canvas.setStrokeColor(black)
    divLineX = boxLeftX + (boxWidth/2)
    canvas.line(divLineX, boxTopY, divLineX, boxBottomY)
    
    # Draw the labels
    canvas.setFillColor(black)
    canvas.setFont("LS", 5)
    skillY = lineStartY
    canvas.drawString(boxLeftX + padding, skillY, "ATK")
    canvas.line(boxLeftX, skillY - 1, boxLeftX + boxWidth, skillY - 1)
    canvas.drawString(diceLeftX, skillY, 'D6')
    
    skillY = skillY - lineHeight - 1
    canvas.drawString(boxLeftX + padding, skillY, "DEF")
    canvas.line(boxLeftX, skillY - 1, boxLeftX + boxWidth, skillY - 1)
    canvas.drawString(diceLeftX, skillY, 'D6')
    
    skillY = skillY - lineHeight - 1
    canvas.drawString(boxLeftX + padding, skillY, "EW")
    canvas.line(boxLeftX, skillY - 1, boxLeftX + boxWidth, skillY - 1)
    canvas.drawString(diceLeftX, skillY, 'D6')
    
    skillY = skillY - lineHeight - 1
    canvas.drawString(boxLeftX + padding, skillY, "LD")
    canvas.line(boxLeftX, skillY - 1, boxLeftX + boxWidth, skillY - 1)
    canvas.drawString(diceLeftX, skillY, 'D6')
    
    # Finally outline the box
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, boxBottomY, boxWidth, boxHeight, fill=0, stroke=1)
    
def drawActions(canvas, origin, actionCount):
    boxWidth = 42
    boxHeight = 13
    boxLeftX = (origin[0]) + 22
    boxTopY = (origin[1]) + boxHeight + padding + 83
    
    titleHeight = 5
    boxDims = 4
    boxCount = 5
    
    titleBottomY = boxTopY - titleHeight
    boxY = titleBottomY - padding - boxDims
    boxSpace = boxDims + padding + padding
    
    # Draw the title box
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, titleBottomY,  boxWidth, titleHeight,  stroke=0, fill=1)    
    canvas.setFillColor(white)    
    canvas.setFont("LS-Bold", 4)
    canvas.drawString(boxLeftX + padding, boxTopY- (titleHeight-1), "ACTONS")
    
    # Finally, draw the boxes
    canvas.setStrokeColor(black)    
    for boxNum in range(boxCount):
        if boxNum + 1 > actionCount:
            canvas.setStrokeColor(lightgrey)
        
        boxX = boxLeftX + padding + 1 + (boxSpace * boxNum)
        canvas.rect(boxX, boxY, boxDims, boxDims)
    
    # Finally outline the entire thing
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, boxTopY - boxHeight, boxWidth, boxHeight, fill=0, stroke=1)

def drawTraits(canvas, origin, model):
    
    traits_move = model.traits_move
    traits_def = model.traits_def
    traits_ew = model.traits_ew
    traits_aux = model.traits_aux
    traits_misc = model.traits_misc
    
    # Define our dimensions
    origin_x = origin[0]
    origin_y = origin[1]
    
    boxWidth = 76
    boxHeight = 66
    boxLeftX = (origin_x + cWidth) - (boxWidth + padding)
    boxBottomY = (origin_y + cHeight) - boxHeight - 25
    
    titleHeight = 5
    headerHeight = 5
    lineHeight = 5
    
    perkBoxHeight = 2 * lineHeight + padding
    
    moveTopY = boxBottomY + boxHeight 
    moveBottomY = moveTopY - lineHeight * 2
    
    defTopY = moveBottomY - (padding * 2) - 1
    defBottomY = defTopY - lineHeight * 2
    
    ewTopY= defBottomY - (padding * 2) - 1
    ewBottomY = ewTopY - lineHeight * 2
    
    auxTopY = ewBottomY - (padding * 2) - 1
    auxBottomY = auxTopY - lineHeight * 2
    
    miscTopY= auxBottomY - (padding * 2) - 1
    miscBottomY = miscTopY - lineHeight * 2

    # Now the datalines    
    canvas.setFont("LS-Bold", 4)
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, moveTopY, boxWidth, lineHeight, stroke=0, fill=1)
    canvas.setFillColor(white)
    canvas.drawString(boxLeftX + padding, moveTopY + 1, "MOVE TRAITS")
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, moveBottomY, boxWidth, lineHeight *3,  stroke=1)    
    drawTraitsBox(canvas, traits_move, (boxLeftX, moveTopY - 1), boxWidth)
    
    canvas.setFont("LS-Bold", 4)
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, defTopY, boxWidth, lineHeight, stroke=0, fill=1)
    canvas.setFillColor(white)
    canvas.drawString(boxLeftX + padding, defTopY + 1, "DEF TRAITS")
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, defBottomY, boxWidth, lineHeight *3,  stroke=1)
    drawTraitsBox(canvas, traits_def, (boxLeftX, defTopY - 1), boxWidth)
    
    canvas.setFont("LS-Bold", 4)
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, ewTopY, boxWidth, lineHeight, stroke=0, fill=1)
    canvas.setFillColor(white)
    canvas.drawString(boxLeftX + padding, ewTopY + 1, "EW TRAITS")
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, ewBottomY, boxWidth, lineHeight *3,  stroke=1)
    drawTraitsBox(canvas, traits_ew, (boxLeftX, ewTopY- 1), boxWidth)
    
    canvas.setFont("LS-Bold", 4)
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, auxTopY, boxWidth, lineHeight, stroke=0, fill=1)
    canvas.setFillColor(white)
    canvas.drawString(boxLeftX + padding, auxTopY + 1, "AUX TRAITS")
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, auxBottomY, boxWidth, lineHeight *3,  stroke=1)
    drawTraitsBox(canvas, traits_aux, (boxLeftX, auxTopY - 1), boxWidth)
    
    canvas.setFont("LS-Bold", 4)
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, miscTopY, boxWidth, lineHeight, stroke=0, fill=1)
    canvas.setFillColor(white)
    canvas.drawString(boxLeftX + padding, miscTopY + 1, "MISC TRAITS")
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, miscBottomY, boxWidth, lineHeight *3,  stroke=1)
    drawTraitsBox(canvas, traits_misc, (boxLeftX, miscTopY - 1), boxWidth)
    
def drawTraitsBox(canvas, traitsList, origin, boxWidth):
    print "Drawing traits box of %i width at position: (%i,%i)" % (boxWidth, origin[0], origin[1])
    
    lineHeight = 4
    origin_x = origin[0]
    origin_y = origin[1] - (lineHeight * 2)

    boxHeight = (2 * lineHeight) + 1
    secY = origin_y + 1
    priY = secY + lineHeight

    canvas.setFillColor(black)
    canvas.setFont("LS", 3)    
    traitL = []
    for trait in traitsList:
        traitL.append(trait.label)
    labelS = ", ".join(traitL)
    print "traitsString is: \n%s\n" % labelS

    # Determine if we need to wrap the text    
    # characters tend to take 2 pixels; but sometimes just 1; just fudge with a 2/3 measure
    wrapWidth = (boxWidth - (2 * padding)) * 2/3
    if len(labelS)  > wrapWidth: 
        print "Line it too long, trying to truncate"
        index = labelS.rfind(",", 0, wrapWidth)
        print "  index is: %i" % index
        lineOne = labelS[0:index].strip()
        print "LineOne is: ", lineOne
        canvas.drawString(origin[0] + padding, priY, lineOne)

        lineTwo = labelS[index+1:].strip()
        print "LineTwo is: ", lineTwo
        canvas.drawString(origin[0] + padding, secY, lineTwo)        
    else:
        canvas.drawString(origin[0] + padding, priY, labelS)
        
''' Non-wrapping reference version'''
def drawTraitsBox2(canvas, traitsList, origin, boxWidth):
    print "Drawing traits box of %i width at position: (%i,%i)" % (boxWidth, origin[0], origin[1])
    
    lineHeight = 4
    origin_x = origin[0] # left corner of our box
    origin_y = origin[1] # top of our box
    label_x = origin_x + padding
    desc_x = label_x + 34

    canvas.setFillColor(black)
    
    currY = origin_y - lineHeight + 1
    for trait in traitsList:
        traitLabelS = "%-6s" % (trait.label)
        traitDescS = "%s" % (trait.desc)
        canvas.setFont("LS-Bold", 4)
        canvas.drawString(label_x, currY, traitLabelS)
        canvas.setFont("LS", 4)
        canvas.drawString(desc_x, currY, traitDescS)
        #print "Drawing line at y=%i" % currY
        currY -= lineHeight + 1


def drawZebraStripes(canvas,  startX,  stripeWidth,  startY,  numStripes,  stripeHeight=6):
   for stripe in range(numStripes):   
        #print "Drawing stripe %i" % stripe
        if stripe % 2 == 0:
            canvas.setFillColor(white)
        else:
            canvas.setFillColor(lightgrey)
        stripeBottomY = startY - (stripeHeight * (stripe + 1)) 
        #print "  Stripe bottomY = %i" % stripeBottomY
        #print "%i / %i / %i / %i" % (startX, stripeBottomY, startX + stripeWidth, stripeHeight)
        canvas.rect(startX, stripeBottomY,  stripeWidth, stripeHeight, stroke=0, fill=1)

def drawReferenceTraits(canvas,  origin,  model):
        
    traits_move = model.traits_move
    traits_def = model.traits_def
    traits_ew = model.traits_ew
    traits_aux = model.traits_aux
    traits_misc = model.traits_misc
    
    # Define our dimensions
    origin_x = origin[0] 
    origin_y = origin[1]    
    boxWidth = cWidth - padding * 2
    boxHeight = cHeight - padding
    
    boxLeftX = origin_x + cWidth + padding
    boxTopY = (origin_y + cHeight) - padding 
    boxBottomY = origin_y + (cHeight / 2) + padding
    
    titleHeight = 5
    headerHeight = 5
    lineHeight = 5
    
    perkBoxHeight = 3 * lineHeight
    boxPad = padding * 4
    
    moveTopY = boxTopY - titleHeight
    moveBottomY = moveTopY - perkBoxHeight
    
    defTopY = moveBottomY - boxPad
    defBottomY = defTopY - perkBoxHeight
    
    ewTopY= defBottomY - boxPad
    ewBottomY = ewTopY - perkBoxHeight
    
    auxTopY = ewBottomY - boxPad
    auxBottomY = auxTopY - perkBoxHeight
    
    miscTopY= auxBottomY - boxPad
    miscBottomY = miscTopY - perkBoxHeight
    
    weapTopY = miscBottomY - boxPad
    weapBottomY = origin_y + padding
    weapHeight = weapTopY - weapBottomY

    # Now the datalines    
    canvas.setFont("LS-Bold", 4)
    drawZebraStripes(canvas,  boxLeftX,  boxWidth,  moveTopY,  3,  5)
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, moveTopY, boxWidth, lineHeight, stroke=0, fill=1)
    canvas.setFillColor(white)
    canvas.drawString(boxLeftX + padding, moveTopY + 1, "MOVE TRAITS")
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, moveBottomY, boxWidth, lineHeight *3,  stroke=1)    
    drawTraitsBox2(canvas, traits_move, (boxLeftX, moveTopY - 1), boxWidth)
    
    canvas.setFont("LS-Bold", 4)
    drawZebraStripes(canvas,  boxLeftX,  boxWidth,  defTopY,  3,  5)
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, defTopY, boxWidth, lineHeight, stroke=0, fill=1)
    canvas.setFillColor(white)
    canvas.drawString(boxLeftX + padding, defTopY + 1, "DEF TRAITS")
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, defBottomY, boxWidth, lineHeight *3,  stroke=1)
    drawTraitsBox2(canvas, traits_def, (boxLeftX, defTopY - 1), boxWidth)
    
    canvas.setFont("LS-Bold", 4)
    drawZebraStripes(canvas,  boxLeftX,  boxWidth,  ewTopY,  3,  5)
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, ewTopY, boxWidth, lineHeight, stroke=0, fill=1)
    canvas.setFillColor(white)
    canvas.drawString(boxLeftX + padding, ewTopY + 1, "EW TRAITS")
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, ewBottomY, boxWidth, lineHeight *3,  stroke=1)
    drawTraitsBox2(canvas, traits_ew, (boxLeftX, ewTopY - 1), boxWidth)
    
    canvas.setFont("LS-Bold", 4)
    drawZebraStripes(canvas,  boxLeftX,  boxWidth,  auxTopY,  3,  5)
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, auxTopY, boxWidth, lineHeight, stroke=0, fill=1)
    canvas.setFillColor(white)
    canvas.drawString(boxLeftX + padding, auxTopY + 1, "AUX TRAITS")
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, auxBottomY, boxWidth, lineHeight *3,  stroke=1)
    drawTraitsBox2(canvas, traits_aux, (boxLeftX, auxTopY - 1), boxWidth)
    
    canvas.setFont("LS-Bold", 4)
    drawZebraStripes(canvas,  boxLeftX,  boxWidth,  miscTopY,  3,  5)
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, miscTopY, boxWidth, lineHeight, stroke=0, fill=1)
    canvas.setFillColor(white)
    canvas.drawString(boxLeftX + padding, miscTopY + 1, "MISC TRAITS")
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, miscBottomY, boxWidth, lineHeight *3,  stroke=1)
    drawTraitsBox2(canvas, traits_misc, (boxLeftX, miscTopY - 1), boxWidth)
    
    canvas.setFont("LS-Bold", 4)
    drawZebraStripes(canvas,  boxLeftX,  boxWidth,  weapTopY,  10,  5)
    canvas.setFillColor(black)
    canvas.rect(boxLeftX, weapTopY, boxWidth, lineHeight, stroke=0, fill=1)
    canvas.setFillColor(white)
    canvas.drawString(boxLeftX + padding, weapTopY + 1, "WEAPON TRAITS")
    canvas.setStrokeColor(black)
    canvas.rect(boxLeftX, weapBottomY, boxWidth, weapHeight,  stroke=1)
    
    # Composite our weapon traits
    traits_dict = {}
    weapons = model.weapons_ranged + model.weapons_thrown + model.weapons_melee
    for weapon in weapons:
        traits = weapon.traits
        for traitO in traits:
            if traitO.label not in traits_dict:
                traits_dict[traitO.label] = traitO

    weap_traits = []
    keys = traits_dict.keys()
    keys.sort()
    for key in keys:
        traitO = traits_dict[key]
        weap_traits.append(traitO)
    
    drawTraitsBox2(canvas, weap_traits, (boxLeftX, weapTopY - 1), boxWidth)
'''
    Draw a test output sheet
'''
def drawTest(modelsDict):
    c = canvas.Canvas("hgbfe_test.pdf",  pagesize=letter)
    origin = (0, 0)
    modelCount = 0

    pp = pprint.PrettyPrinter(indent=4)
    
    keys = modelsDict.keys()
    keys.sort()
    
    for key in keys:
        model = modelsDict[key]
        origin = (0,  modelCount * cHeight)
        print "\n\nDrawing model named %s at coords (%i, %i)" % (model.name,  origin[0],  origin[1])
        
        drawBorder(c,  origin)        
        # Broken in PIL 1.1.7-1
        drawBackground(c, origin) 
        drawTitle(c, origin, model.name,  modelCount)
        drawActions(c, origin, model.actions)
        
        drawSkills(c,  origin)
        leadership = 0
        priorityLevel = 0
        drawLD(c, origin, leadership, priorityLevel)
        
        # Draw damage  box
        damageS = model.damage[::-1]
        armorMulti = (len(damageS) + 1 )         
        damageDict = {
                      6 : {  'front': str(model.armor * armorMulti),  'rear': str(model.armor_rear * armorMulti),  'boxType' : u'D' }, 
            }
        
        idx = 5
        for boxType in damageS:
            armorMulti = armorMulti - 1
            damageDict[idx] = { 'front': str(model.armor * armorMulti),  'rear': str(model.armor_rear * armorMulti),  'boxType' : boxType }
            idx = idx - 1
        while (idx != -1):
            damageDict[idx] = {  'front': '', 'rear': '', 'unused': True }
            idx = idx -1
        #pp.pprint(damageDict)
        drawArmor(c, origin,  damageDict)
        
        # Draw movement box
        moveDict = {}
        moveDict[0] = { 'type': model.movePriTypeS,  'movePoints' : str(model.movePriMP),  'atkMod': "%+i" % (model.atkmod), 'defMod': "%+i" % (model.defmod) }
        if model.moveSecType is not None:
            moveDict[1] = { 'type':model.moveSecTypeS,  'movePoints' : str(model.moveSecMP),  'atkMod': "%+i" % (model.atkmod), 'defMod': "%+i" % (model.defmod) }
        drawMovement(c,  origin,  moveDict)
        
        # Draw EW box
        ewDict = { 'detect' : model.detect,  'sensors': model.sensors, 'autocomm' : model.autocomm,  'comm': model.comm,  'ecm' : 0,  'eccm': 0 }
        for trait in model.traits_aux:
            if trait.name.startswith('ecm'):
                ewDict['ecm'] = trait.rating
            if trait.name.startswith('eccm'):
                ewDict['eccm'] = trait.rating
        drawEW(c, origin, ewDict)
        
        # Draw Ranged Weapons
        weaponsDict  = {}
        weaponL = []
        for weapon in model.weapons_ranged:
            print "Found weapon: %s" % weapon.name
        idx = 0
        weaponL = sorted(model.weapons_ranged,  weaponCmp)
        for weapon in weaponL:
            #print "Found weapon: %s" % weapon.name
            #print "weapon range is: %i" % weapon.rangeEX
            weaponsDict[idx] = { 
            'name': weapon.name.upper(), 
            'arc': weapon.arcS.upper(), 
            'rangePR': str(weapon.rangePR),  
            'rangeCR': str(weapon.rangeCR), 
            'rangeER': str(weapon.rangeER), 
            'dam': str(weapon.dam),
            'special': weapon.traitsS, 
            'ammo': weapon.ammo,
            }
            idx += 1
        drawRangedWeapons(c, origin,  weaponsDict)
        
        # Thrown Weapons
        weaponsDict.clear()
        idx = 0
        weaponL = sorted(model.weapons_thrown,  weaponCmp)
        for weapon in weaponL:
            #print "Found weapon: %s" % weapon.name
            #print "weapon range is: %i" % weapon.rangeEX
            weaponsDict[idx] = { 
            'name': weapon.name.upper(),
            'arc': weapon.arcS.upper(),        
            'range': str(model.size / 2), 
            'dam': str(weapon.dam),
            'special': weapon.traitsS, 
            'ammo': weapon.ammo,
            }
            idx += 1
        drawThrownWeapons(c, origin,  weaponsDict)
        
        # Melee Weapons
        weaponsDict.clear()
        idx = 0
        weaponL = sorted(model.weapons_melee,  weaponCmp)
        for weapon in weaponL:
            #print "Found weapon: %s" % weapon.name
            #print "weapon range is: %i" % weapon.rangeEX
            weaponDam = weapon.dam
            if weapon.name.lower() != 'pa' and weaponDam < 10:
                weaponDam = (model.size*2) + (weapon.dam)
                print "Setting weapon [%s] to damage [%i]" % (weapon.name.lower(),  weaponDam)
            weaponsDict[idx] = { 
            'name': weapon.name.upper(),
            'arc': weapon.arcS.upper(),                    
            'dam': str(weaponDam),
            'special': weapon.traitsS, 
            'ammo': weapon.ammo,
            }
            idx += 1
        drawMeleeWeapons(c, origin,  weaponsDict)
        
        # Traits on the main card
        drawTraits(c,  origin,  model)
        
        # Now generate the refernce card
        drawReferenceTraits(c,  origin,  model)
        
        # Increment our origin
        if modelCount != 0 and modelCount % 3 == 0:
            c.showPage()
            modelCount = 0
        else:
            modelCount += 1
    # endof  for key, model in modelsDict.iteritems():   
    
    # Catch any runover models
    if modelCount != 0:
        c.showPage()

    # Save the output and exit
    c.save()
# endof drawTest

if __name__ == '__main__':
    # Create the canvas we use as the 'file'
    #c = canvas.Canvas("hgbfe_test.pdf", pagesize=(cWidth, cHeight))
    c = canvas.Canvas("hgbfe_test.pdf",  pagesize=letter)
    #c = canvas.Canvas("test.pdf", pagesize=(2*cWidth, cHeight))
    
    # Start mocking up origin to rewrite sizing based upon adjustable cards
    #   This will let us do 8-up pages, for instance.
    origin = (0,0)
    drawBorder(c, origin)
    # Broken in PIL 1.1.7-1
    drawBackground(c, origin)
    unitName = "LHT-67"
    drawTitle(c, origin, unitName)
    
    damageDict = {
              0: { 'front': '',  'rear': '', 'unused': True}, 
              1: { 'front': '20',  'rear': '18', 'boxType': 's'}, 
              2: { 'front': '40',  'rear': '36', 'boxType': 's'}, 
              3: { 'front': '60',  'rear': '54', 'boxType': 'l'}, 
              4: { 'front': '80',  'rear': '72', 'boxType': 'h'}, 
              5: { 'front': '120',  'rear': '90', 'boxType': 'c'}, 
              6: { 'front': '140',  'rear': '108', 'boxType': 'd'}, 
              }
    drawArmor(c, origin,  damageDict)
    
    drawSkills(c, origin)
    
    actionCount = 1;    
    drawActions(c, origin, actionCount)
    
    moveDict = {
        0: {
            'type' : 'Walker',            
            'movePoints' : '4',
            'atkMod' : '-1',
            'defMod' : '+1',
            },
        1: {
            'type' : 'Hover',            
            'movePoints' : '12',
            'atkMod' : '+1',
            'defMod' : '-1',
            },
    }
    drawMovement(c, origin, moveDict)
    
    ewDict = {
        'detect' : 3,
        'sensors': 0,
        'autocomm': 4,
        'comm': 1,
        'ecm': 0,
        'eccm': 0,
    }
    drawEW(c, origin, ewDict)
    
    leadership = 0
    priorityLevel = 0
    drawLD(c, origin, leadership, priorityLevel)
    
    weaponsDict = {
        0: {
            'name' :'VHIRP/48', 
            'arc' :'T1', 
            'rangePR': '8', 
            'rangeCR': '32',
            'rangeER' :'64', 
            'dam': "x16",  
            'special' :'AE4, Ba4, HEAT, Inacc, SB', 
            'ammo' : 'OOOO', 
        }, 
        1 : {
            'name' :'LAC', 
            'arc' :'A', 
            'rangePB': '6', 
            'rangeCB': '24',
            'rangeEX' :'48', 
            'dam': "x8",  
            'special' :'Bu1', 
            'ammo' : '-', 
        }, 
        2 : {
            'name' :'HRF', 
            'arc' :'A', 
            'rangePB': '98', 
            'rangeCB': '999',
            'rangeEX' :'999', 
            'dam': "x12",  
            'special' :'', 
            'ammo' : '-', 
        }, 
    }
    drawRangedWeapons(c, origin,  weaponsDict)
    
    thrownDict = {
        0: {
            'name' :'HHG',             
            'range': '3', 
            'dam': "x25",  
            'special' :'AE1', 
            'ammo' : 'OO', 
        }, 
        1: {
            'name' :'HWG',             
            'range': '3', 
            'dam': "x15",  
            'special' :'AE1, H', 
            'ammo' : 'OO', 
        },         
    }
    drawThrownWeapons(c, origin, thrownDict)
    
    meleeDict = {
        0: {
            'name' :'VB', 
            'arc' :'F',             
            'dam': "x8",  
            'special' :'LM',
        }, 
        1: {
            'name' :'HSG', 
            'arc' :'F', 
            'dam': "x22",  
            'special' :'AP, HM', 
            'ammo' : 'OO', 
        },         
    }
    drawMeleeWeapons(c, origin, meleeDict)
    
    perks = [ "targetdesignator_2",  "backupcomms", "sensordependent", "improvedoffroad",  "arms",  "lowprofile", "improvedreardefense" ,
    "weakfacing-underside",
    "exposedaux",
    "exposedfirecon" ,
    "exposedmovement",
    "fireresistant" ,
    "haywireresistant",
    "ruggedmovement" ,
    "shieldedweapons", 
    "vulnerabletohaywire",]
    drawPerks(c, origin, perks)
    
    c.showPage()

    # Save the output and exit
    c.save()
    print "Done!"
